package com.pospi.xstore.ui.diaob;

import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.widget.DrawerLayout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.maning.library.MClearEditText;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.mylhyl.circledialog.view.listener.OnCreateBodyViewListener;
import com.pospi.xstore.R;
import com.pospi.xstore.dao.GoodsDao;
import com.pospi.xstore.dto.Brand;
import com.pospi.xstore.dto.GoodsBeen;
import com.pospi.xstore.dto.MenuDto;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.ui.bh.SupDetailActivity;
import com.pospi.xstore.ui.xs.OutDetailActivity;
import com.pospi.xstore.ui.xs.RefundDetailActivity;
import com.pospi.xstore.ui.xs.SaleDetailActivity;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.Constant;
import com.pospi.xstore.util.DoubleSave;
import com.pospi.xstore.util.SaveOrderInfo;
import com.pospi.xstore.util.TurnSize;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import lib.kingja.switchbutton.SwitchMultiButton;


public class PointGoodsActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    @Bind(R.id.lv_goods_list)
    ListView lv_goods_list;
    @Bind(R.id.iv_search_xz)
    ImageView iv_search_xz;
    @Bind(R.id.et_code_counts)
    EditText et_code_counts;
    @Bind(R.id.button_swith)
    SwitchMultiButton button_swith;
    @Bind(R.id.v4_listview)
    ListView v4_listview;
    @Bind(R.id.v4_drawerlayout)
    DrawerLayout drawerlayout_left;
    @Bind(R.id.ll_bottom)
    LinearLayout ll_bottom;

    List<GoodsBeen> goodsDtos = new ArrayList<>();

    private String headers[] = {"分类"};
    private List<View> popupViews = new ArrayList<>();
    private String constellations[] = {"不限", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座", "水瓶座", "双鱼座"};
    private Myadapter myadapter;
    private GoodsDao dao;
    private String market;
    private String supid;
    private DialogFragment dialog;
    private ArrayAdapter<String> adapter;
    List<String> catlist = new ArrayList<>();
    String chooseType = "0";
    private String mId="";
    private String bId="";
    private GoodsDetailAdapter goodsDetailAdapter;
    private PopupWindow mPricePopupWindow;
    private String mark;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_point2);
        ButterKnife.bind(this);
        setTitle("商品查询");
        mark = getIntent().getStringExtra("mark");//标记那个页面请求的
        init();
        downBrand();
        downMenu();
    }
    private void setItem(){
        downGoods(1,100);
        mId = "";
        bId = "";
        drawerlayout_left.closeDrawers();
    }
    private void init() {



        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, catlist);
        v4_listview.setAdapter(adapter);
        v4_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                switch (chooseType) {
                    case "0":
                        mId = menuDtos.get(i).getSid();
                       setItem();

                        break;
                    case "1":
                        bId = brands.get(i).getId();
                     setItem();
                        break;
                }
            }
        });




        button_swith.setText("类别","品牌","其它");
        button_swith.setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @Override
            public void onSwitch(int position, String tabText) {
                switch (position) {
                    case 0:
                        chooseType = "0";
                        catlist.clear();
                        for (MenuDto menuDto : menuDtos) {
                            catlist.add(menuDto.getName());
                        }
                        adapter.notifyDataSetChanged();
                        break;
                    case 1:
                        chooseType = "1";
                        catlist.clear();
                        for (Brand brand : brands) {
                            catlist.add(brand.getName());
                        }
                        adapter.notifyDataSetChanged();
                        break;
                    case 2:
                        chooseType = "2";
                        catlist.clear();
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        });


        market = getIntent().getStringExtra("market");
        supid = getIntent().getStringExtra("supid");

        dao = new GoodsDao(getApplicationContext());

        myadapter = new Myadapter();
        lv_goods_list.setAdapter(myadapter);
        lv_goods_list.setOnItemClickListener(this);

    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
    private boolean isHide = false;
    private void hintKbOne() {
        if (isHide) {
            InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
            // 得到InputMethodManager的实例
            if (imm.isActive()) {
                // 如果开启
                imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                        InputMethodManager.HIDE_NOT_ALWAYS);

            }
            isHide = false;
        }

    }
    private MClearEditText sl;
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        //点击商品
        goodsDto = goodsDtos.get(i);
        new CircleDialog.Builder(this)
                .setBodyView(R.layout.dialog_point, new OnCreateBodyViewListener() {
                    @Override
                    public void onCreateBodyView(View view) {
                        sl = view.findViewById(R.id.et_goods_num);
//                        dj = view.findViewById(R.id.et_goods_dj);
                        sl.setText("0");
                        sl.setOnClearClickListener(new MClearEditText.OnClearClickListener() {
                            @Override
                            public void onClick() {
                                isHide = true;
                            }
                        });
                    }
                })
                .setPositive("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        hintKbOne();
                        if (isNumber(sl.getText().toString().trim())) {
                            goodsDto.setSl(Double.parseDouble(sl.getText().toString().trim()));
                            goodsDto.setChoose(true);
                            myadapter.notifyDataSetChanged();
                            addGoods(goodsDto);

                        }

                    }
                })
                .setCancelable(false)
                .setTitle(goodsDto.getName())
                .setNegative("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        hintKbOne();
                    }
                })
                .show();
    }
    //添加商品
    private void addGoods(GoodsBeen goodsDto) {
            goodinfos.add(goodsDto);

    }

    class Myadapter extends BaseAdapter{

        @Override
        public int getCount() {
            return goodsDtos.size();
        }

        @Override
        public Object getItem(int i) {
            return goodsDtos.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Holder holder;
            if (view == null) {
                holder = new Holder();
                view = LayoutInflater.from(PointGoodsActivity.this).inflate(R.layout.search_list_item, null);
                holder.showview = view.findViewById(R.id.showview);
                holder.textItem = view.findViewById(R.id.textItem);
                holder.money = view.findViewById(R.id.money);
                holder.barcode = view.findViewById(R.id.barcode);
                holder.tv_spec = view.findViewById(R.id.tv_spec);
                view.setTag(holder);

            } else {
                holder = (Holder) view.getTag();
            }
            holder.textItem.setText(goodsDtos.get(i).getName());
            holder.money.setText(String.valueOf(goodsDtos.get(i).getDj()));
            holder.tv_spec.setText(goodsDtos.get(i).getSpec()+goodsDtos.get(i).getUnit());
            holder.barcode.setText(goodsDtos.get(i).getBarcode());


            return view;
        }

    }
    private class Holder{
        ImageView showview;
        TextView textItem;
        TextView money;
        TextView barcode;
        TextView tv_spec;
    }
    //下载商品
    private void downGoods(int page,int limit) {
        showDialog();
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "bill.mbilldb");
        params.put("type", "107");
        params.put("fun", "find_goods");

        params.put("page", page);
        params.put("limit", limit);

        params.put("outmarket", market);
        params.put("inmarket", supid);
        params.put("market", market);

        JSONObject object = new JSONObject();
        try {
            if (mId.isEmpty() && bId.isEmpty()) {
                object.put("filter", et_code_counts.getText().toString().trim());
            } else {
                object.put("catid", mId);
                object.put("brandid", bId);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        params.put("pds",object);

        Log.i("goods", params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, final byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    final JSONObject object1 = new JSONObject(new String(bytes));
                    Log.i("login", object1.getString("errMsg"));
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                saveGoods(object1.getJSONArray("result"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

                } catch (JSONException e) {
                    e.printStackTrace();
                }



            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });

    }

    private void saveGoods(JSONArray s) {
        List<GoodsBeen> list = SaveOrderInfo.changegoodsToList(s.toString());
        goodsDtos.clear();
        goodsDtos.addAll(list);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                close();
                if (goodsDtos.size() == 0) {
                    Toast.makeText(PointGoodsActivity.this, "未查询到数据", Toast.LENGTH_SHORT).show();
                }
                myadapter.notifyDataSetChanged();
            }
        });


    }

    @OnClick({R.id.iv_search_xz,R.id.order_detail, R.id.settle, R.id.retain,R.id.iv_cat})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_cat:
                drawerlayout_left.openDrawer(Gravity.LEFT);
                break;
            case R.id.iv_search_xz:
               downGoods(1,100);
                break;
            case R.id.retain:
                LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                View contentView = mLayoutInflater.inflate(R.layout.pointselect_detail, null);
                // R.layout.pop为PopupWindow 的布局文件
                PopupWindow pop = new PopupWindow(contentView, ActionBar.LayoutParams.MATCH_PARENT, TurnSize.dip2px(getApplicationContext(), 300));
                pop.setBackgroundDrawable(new BitmapDrawable());
                // 指定 PopupWindow 的背景
                pop.setFocusable(true);
                //指定PopupWindow显示在你指定的view下

                int[] location = new int[2];
                ll_bottom.getLocationOnScreen(location);
                pop.showAtLocation(ll_bottom, Gravity.NO_GRAVITY, location[0], location[1] - pop.getHeight());

                ListView info = (ListView) contentView.findViewById(R.id.lv_detail);
                goodsDetailAdapter = new GoodsDetailAdapter(getApplicationContext(), goodinfos);
                info.setAdapter(goodsDetailAdapter);
//                Constant.fixListViewHeight(info);
                RelativeLayout ll = (RelativeLayout) contentView.findViewById(R.id.delete);
                ll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        goodinfos.clear();
                        goodsDetailAdapter.notifyDataSetChanged();
                    }
                });
                break;
            case R.id.settle:
                if (goodinfos.size() == 0) {
                    Toast.makeText(this, "未选择商品", Toast.LENGTH_SHORT).show();
                    return;
                }
                back();


                break;
        }
    }

    //返回到指定页面
    private void back() {
        switch (mark) {
            case "DboOutDetailActivity":
                Intent intentCgDetai = new Intent(this, DboOutDetailActivity.class);
                intentCgDetai.putExtra("data", SaveOrderInfo.changetoToJson(goodinfos));
                startActivity(intentCgDetai);
                break;
            case "SupDetailActivity":
                Intent intenSupDetail = new Intent(this, SupDetailActivity.class);
                intenSupDetail.putExtra("data", SaveOrderInfo.changetoToJson(goodinfos));
                startActivity(intenSupDetail);
                break;
            case "PsOutDetailActivity":
                Intent ps = new Intent(this, PsOutDetailActivity.class);
                ps.putExtra("data", SaveOrderInfo.changetoToJson(goodinfos));
                startActivity(ps);
                break;
        }


        finish();
    }

    //已选商品
    List<GoodsBeen> goodinfos = new ArrayList<>();
    private double totalMoney = 0;
    class GoodsDetailAdapter extends BaseAdapter {
        private Context context;
        private List<GoodsBeen> shoppings;

        public GoodsDetailAdapter(Context context, List<GoodsBeen> goodsDtos) {
            this.context = context;
            this.shoppings = goodsDtos;
        }

        @Override
        public int getCount() {
            return shoppings.size();
        }

        @Override
        public Object getItem(int position) {
            return shoppings.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.pointselect_detail_item, null);
                holder = new ViewHolder();
                holder.name = (TextView) convertView.findViewById(R.id.goods_name);
                holder.price = (TextView) convertView.findViewById(R.id.goods_price);
                holder.num = (TextView) convertView.findViewById(R.id.goods_num);
                holder.add = (ImageView) convertView.findViewById(R.id.add_num);
                holder.js = (ImageView) convertView.findViewById(R.id.substract_goods);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            String mo = "";

            holder.name.setText(goodsDtos.get(position).getName());
            holder.num.setText(goodsDtos.get(position).getSl()+"");

           final double goodsPrice = shoppings.get(position).getDj();
            holder.price.setText(goodsPrice+"");

            holder.add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    shoppings.get(position).setSl(DoubleSave.doubleSaveTwo(shoppings.get(position).getSl() + 1));
                    holder.num.setText(String.valueOf(DoubleSave.doubleSaveTwo(shoppings.get(position).getSl())));
                    totalMoney += goodsPrice;
//                    tvMoney.setText(decimalFormat.format(DoubleSave.doubleSaveTwo(totalMoney)));
                }
            });
            holder.js.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (shoppings.get(position).getSl() - 1 > 0) {
                        goodsDtos.get(position).setSl(DoubleSave.doubleSaveTwo(shoppings.get(position).getSl() - 1));
                        holder.num.setText(String.valueOf(DoubleSave.doubleSaveTwo(shoppings.get(position).getSl())));
                    } else {
                        shoppings.remove(position);
                    }
                    goodsDetailAdapter.notifyDataSetChanged();
                    totalMoney -= goodsPrice;
                    if (totalMoney < 0) {
                        totalMoney = 0;
                    }
//                    tvMoney.setText(decimalFormat.format(DoubleSave.doubleSaveTwo(totalMoney)));
                }
            });
            return convertView;
        }

        class ViewHolder {
            TextView name;
            TextView price;
            TextView num;
            ImageView add;
            ImageView js;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        goodsDtos.clear();
    }


     List<MenuDto> menuDtos = new ArrayList<>();
    List<Brand> brands = new ArrayList<>();
    //下载分类
    private void downMenu() {

        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getlastgoodscat");
        Log.i("goods", params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    for (int j=0;j<result.length();j++) {
                        MenuDto menuDto = new MenuDto();
                        menuDto.setSid(result.getJSONObject(j).getString("id"));
                        menuDto.setName(result.getJSONObject(j).getString("name"));
                        menuDtos.add(menuDto);
                        catlist.clear();
                        for (MenuDto dto : menuDtos) {
                            catlist.add(dto.getName());
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                adapter.notifyDataSetChanged();
                            }
                        });
                    }
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });

    }
    //下载品牌
    private void downBrand() {
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getlastgoodsbrand");
        Log.i("goods", params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    brands = SaveOrderInfo.changebrandToList(result.toString());
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });

    }
    private GoodsBeen goodsDto;
    private EditText good_weight;
    private void showSetWeightPopupWindow() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.weight_layout, null);
        mPricePopupWindow = new PopupWindow(contentView, getWidth()*2/3, getHeight()*3/5);
        mPricePopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPricePopupWindow.setFocusable(true);
        TextView sure = (TextView) contentView.findViewById(R.id.scan_sure);
//        text_num = (TextView) contentView.findViewById(R.id.text_num);
        good_weight = (EditText) contentView.findViewById(R.id.scan_tv_weight);
        TextView clear_weight = (TextView) contentView.findViewById(R.id.clear_weight);
        clear_weight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                numberAdd = "";
                good_weight.setText("");
            }
        });
        mPricePopupWindow.showAtLocation(drawerlayout_left, Gravity.CENTER, 0, 0);
        mPricePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                numberAdd = "";
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String et = good_weight.getText().toString().trim();
                if (isNumber(et)) {
                    goodsDto.setSl(DoubleSave.doubleSaveTwo(Double.parseDouble(et)));
                    addGoods(goodsDto);
                    numberAdd = "";
                    mPricePopupWindow.dismiss();
                } else {
                    Toast.makeText(PointGoodsActivity.this, "请输入正确的数量", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private String numberAdd = "";

    public void popupWindowNumberClick(View view) {
        TextView tv = (TextView) view;
        if (numberAdd.isEmpty()) {
            if (view.getId() != R.id.dian) {
                numberAdd += tv.getText().toString();
            }
        } else {
            if (numberAdd.equals("0") && view.getId() == R.id.dian) {
                numberAdd = tv.getText().toString();
            } else {
                numberAdd += tv.getText().toString();
            }
        }
        good_weight.setText(numberAdd);
    }
    private int  getWidth(){
        Resources resources = this.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        float density = dm.density;
        return dm.widthPixels;
    }
    private  int getHeight(){
        Resources resources = this.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        float density = dm.density;
        return dm.heightPixels;
    }
    public static boolean isNumber(String str) {
        String reg = "^[0-9]+(.[0-9]+)?$";
        return str.matches(reg);
    }

}
